<template>
  <div v-if="ready" class="l-rblock l-form-viewer" style="padding: 8px 8px 0 8px">
    <el-form
      ref="form"
      :model="formData"
      :rules="rules"
      :size="myFormInfo.size"
      :labelPosition="myFormInfo.labelPosition"
      :label-width="myFormInfo.labelWidth ? `${myFormInfo.labelWidth}px` : '80px'"
    >
      <input type="text" style="display: none" />
      <div :class="['l-auto-window', { 'only-tabs': showTabList.length <= 1 }]">
        <el-tabs v-model="formActiveName" type="card">
          <el-tab-pane
            class="l-tabs-container"
            v-for="(item, index) in showTabList"
            :key="index"
            :label="item.text"
            :name="'tab' + index"
          >
            <el-row :gutter="myFormInfo.gutter">
              <div class="l-rblock">
                <template v-for="col in item.components">
                  <el-col
                    style="margin-bottom: 16px"
                    v-if="['gridtable'].includes(col.type)"
                    :key="col.prop"
                    :span="24"
                  >
                    <div v-if="!$validatenull(col.label)" class="l-title">{{ $t(col.label) }}</div>
                    <l-edit-table
                      :required="col.required"
                      :addBtnText="col.addBtnText"
                      :isAddBtn="col.isAddBtn"
                      :isRemoveBtn="col.isRemoveBtn"
                      :isShowNum="col.isShowNum"
                      :columns="getTableColumns(col.children)"
                      :dataSource="formData[col.prop]"
                      :filterDeleteBtn="filterTableDeleteBtn"
                      :isRead="isRead"
                      @addRow="handleAddRow(col)"
                      @deleteRow="handleDeleteRow($event, col)"
                      :ref="col.prop"
                    >
                      <template v-for="column in col.children" v-slot:[column.prop]="scope">
                        <viewer-form-item
                          :key="column.prop"
                          :isRead="isRead"
                          v-model="scope.row[column.prop]"
                          :upCtrls="upCtrls"
                          :formData="scope.row"
                          :data="column"
                          @change="handleItemChange($event, col, scope.$index, scope.row)"
                        >
                        </viewer-form-item>
                      </template>
                    </l-edit-table>
                  </el-col>
                  <el-col
                    style="margin-bottom: 16px"
                    v-else-if="['viewtable'].includes(col.type)"
                    :key="col.prop"
                    :span="24"
                  >
                    <div v-if="!$validatenull(col.label)" class="l-title">{{ $t(col.label) }}</div>
                    <l-view-table
                      :dataType="col.dataType"
                      :isPage="col.isPage"
                      :apiField="col.apiField"
                      :apiMethod="col.apiMethod"
                      :apiUrl="col.apiUrl"
                      :paramFiled="formData[col.paramFiled]"
                      :columns="col.columns"
                      :apiCode="col.apiCode"
                      :code="col.dataCode"
                    >
                    </l-view-table>
                  </el-col>
                  <el-col v-else-if="!['gridtable'].includes(col.type)" :key="col.prop" :span="col.span">
                    <viewer-form-item v-if="col.type == 'divider'" :data="col"></viewer-form-item>
                    <card-viewer v-else-if="col.type == 'card'" :data="col"></card-viewer>

                    <el-form-item v-else-if="col.type == 'btn'" v-show="col.display && !isRead" labelWidth="0px">
                      <el-button
                        :size="col.size"
                        :plain="col.plain"
                        :round="col.round"
                        :circle="col.circle"
                        :icon="col.myIcon"
                        :type="col.myType"
                        :disabled="col.disabled"
                        @click="componentBtnClick(col)"
                        >{{ col.label }}</el-button
                      >
                    </el-form-item>

                    <el-form-item
                      v-else
                      v-show="col.display"
                      :label="col.label"
                      :labelWidth="col.labelWidth == undefined ? undefined : col.labelWidth + 'px'"
                      :prop="col.prop"
                    >
                      <viewer-form-item
                        v-model="formData[col.prop]"
                        :isRead="isRead"
                        :isForm="true"
                        :upCtrls="upCtrls"
                        :data="col"
                        :formData="formData"
                        @change="handleItemChange"
                      >
                      </viewer-form-item>
                    </el-form-item>
                  </el-col>
                </template>
              </div>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-form>
  </div>
</template>

<script>
import viewerFormItem from "./viewerFormItem";
import cardViewer from "./cardViewer.vue";
export default {
  name: "l-form-viewer",
  components: {
    viewerFormItem,
    cardViewer,
  },
  provide() {
    return {
      formViewer: this,
    };
  },
  props: {
    formInfo: {
      type: Object,
      default: () => {
        return {};
      },
    },
    isAuth: {
      type: Boolean,
      default: false,
    },
    isRead: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      formActiveName: "tab0",
      formData: {},
      oldFormData: null,

      originalTabList: [],
      myFormInfo: {},

      gridtables: [],
      rules: {},
      components: {},

      isUpdate: false,
      loadingObj: null,

      upCtrls: {}, // 级联组件之间的集合

      ready: false,
    };
  },
  computed: {
    tabList() {
      /**对表单字段调整根据权限信息 */
      if (this.isAuth && this.lr_pageAuthInfo && this.lr_pageAuthInfo.isAuth) {
        const tabList = [];

        const authData = this.lr_pageAuthInfo.data.forms;
        const authMap = {};

        authData.forEach((item) => {
          const itemList = item.split(",");
          const propList = itemList[0].split("|");
          if (propList.length > 1) {
            // 表格
            authMap[propList[0]] = authMap[propList[0]] || {};
            authMap[propList[0]][propList[1]] = itemList[1];
          } else {
            // 表单字段
            authMap[itemList[0]] = itemList[1];
          }
        });

        // 放置隐藏组件
        const hideComponents = [];

        this.originalTabList &&
          this.originalTabList.forEach((tab) => {
            const newTab = {
              text: tab.text,
              components: [],
            };

            tab.components.forEach((component) => {
              if (!["gridtable", "card"].includes(component.type)) {
                if (!component.display) {
                  hideComponents.push(component);
                } else if (authMap[component.prop]) {
                  if (authMap[component.prop] != "2") {
                    component.disabled = true;
                    //component.readonly = true
                  }
                  newTab.components.push(component);
                } else if (
                  [
                    "guid",
                    "company",
                    "department",
                    "createuser",
                    "modifyuser",
                    "createtime",
                    "modifytime",
                    "",
                  ].includes(component.type)
                ) {
                  component.display = false;
                  hideComponents.push(component);
                }
              } else if (["gridtable"].includes(component.type)) {
                if (authMap[`${component.prop}_add`]) {
                  if (authMap[`${component.prop}_add`] == "2") {
                    component.isAddBtn = true;
                  } else {
                    component.isAddBtn = false;
                  }
                }

                if (authMap[`${component.prop}_remove`]) {
                  if (authMap[`${component.prop}_remove`] == "2") {
                    component.isRemoveBtn = true;
                  } else {
                    component.isRemoveBtn = false;
                  }
                }

                if (authMap[component.prop]) {
                  newTab.components.push(component);
                  component.children.forEach((cell) => {
                    if (authMap[component.prop][cell.prop]) {
                      if (authMap[component.prop][cell.prop] != "2") {
                        cell.disabled = true;
                        //cell.readonly = true
                      }
                    } else {
                      cell.display = false;
                    }
                  });
                }
              } else if (authMap[component.prop] || ["card"].includes(component.type)) {
                newTab.components.push(component);
              }
            });
            // 不可见的组件单独放置
            if (newTab.components.length > 0) {
              tabList.push(newTab);
            }
          });

        if (tabList.length > 0) {
          tabList[0].components.push(...hideComponents);
        }

        return tabList;
      } else if (this.isWfForm) {
        // 表单的流程权限
        const tabList = [];

        // 放置隐藏组件
        const hideComponents = [];

        this.originalTabList &&
          this.originalTabList.forEach((tab) => {
            const newTab = {
              text: tab.text,
              components: [],
            };

            tab.components.forEach((component) => {
              if (!["gridtable", "card"].includes(component.type)) {
                if (!component.display) {
                  hideComponents.push(component);
                } else if (
                  this.authFieldsMap[component.prop] &&
                  (this.authFieldsMap[component.prop].isEdit || this.authFieldsMap[component.prop].isLook)
                ) {
                  if (!this.authFieldsMap[component.prop].isEdit) {
                    component.disabled = true;
                  }
                  newTab.components.push(component);
                } else if (
                  [
                    "guid",
                    "company",
                    "department",
                    "createuser",
                    "modifyuser",
                    "createtime",
                    "modifytime",
                    "",
                  ].includes(component.type)
                ) {
                  component.display = false;
                  hideComponents.push(component);
                }
              } else if (["gridtable"].includes(component.type)) {
                if (this.authFieldsMap[`${component.prop}_add`]) {
                  if (this.authFieldsMap[`${component.prop}_add`].isEdit) {
                    component.isAddBtn = true;
                  } else {
                    component.isAddBtn = false;
                  }
                }

                if (this.authFieldsMap[`${component.prop}_remove`]) {
                  if (this.authFieldsMap[`${component.prop}_remove`].isEdit) {
                    component.isRemoveBtn = true;
                  } else {
                    component.isRemoveBtn = false;
                  }
                }

                if (this.authFieldsMap[`${component.prop}_required`]) {
                  if (this.authFieldsMap[`${component.prop}_required`].required) {
                    component.required = true;
                  } else {
                    component.required = false;
                  }
                }

                component.children.forEach((cell) => {
                  if (
                    this.authFieldsMap[cell.prop] &&
                    (this.authFieldsMap[cell.prop].isEdit || this.authFieldsMap[cell.prop].isLook)
                  ) {
                    if (!this.authFieldsMap[cell.prop].isEdit) {
                      cell.disabled = true;
                    }
                    if (newTab.components.findIndex((t) => t.prop == component.prop) == -1) {
                      newTab.components.push(component);
                    }
                  } else {
                    cell.display = false;
                  }
                });
              } else if (
                ["card"].includes(component.type) ||
                (this.authFieldsMap[component.prop] &&
                  (this.authFieldsMap[component.prop].isEdit || this.authFieldsMap[component.prop].isLook))
              ) {
                newTab.components.push(component);
              }
            });
            // 不可见的组件单独放置

            if (newTab.components.length > 0) {
              tabList.push(newTab);
            }
          });

        if (tabList.length > 0) {
          tabList[0].components.push(...hideComponents);
        }

        return tabList;
      } else {
        return this.originalTabList || [];
      }
    },
    showTabList() {
      return this.toShowData(this.tabList);
    },
  },
  mounted() {},
  methods: {
    async init(postData) {
      this.ready = false;
      this.isUpdate = !this.$validatenull(postData);

      this.myFormInfo = {};
      this.oldFormData = null;
      this.formData = {};

      const gridtables = [];
      const rules = {};
      const components = {};

      const formInfo = this.$deepClone(this.formInfo);
      // 设置对应数据值
      formInfo.tabList &&
        formInfo.tabList.forEach((tab) => {
          tab.components.forEach((component) => {
            if (!["viewtable", "card", "btn"].includes(component.type)) {
              this.$set(this.formData, component.prop, this.getFormDataValue(component, postData || {}, this.isUpdate));

              if (["gridtable"].includes(component.type)) {
                gridtables.push(component);
                components[component.prop] = component;
                component.children.forEach((col) => {
                  components[col.prop] = col;

                  if (col.upCtrl) {
                    this.upCtrls[col.upCtrl] = this.upCtrls[col.upCtrl] || [];
                    this.upCtrls[col.upCtrl].push(col.prop);
                  }
                });
              } else {
                components[component.prop] = component;
                if (component.upCtrl) {
                  this.upCtrls[component.upCtrl] = this.upCtrls[component.upCtrl] || [];
                  this.upCtrls[component.upCtrl].push(component.prop);
                }
              }

              if (!["gridtable", "viewtable", "card", "btn"].includes(component.type)) {
                if (component.required) {
                  rules[component.prop] = [];
                  rules[component.prop].push({ required: true, message: `请输入${component.label}`, trigger: "blur" });
                }
                if (component.patterns && component.patterns.length > 0) {
                  rules[component.prop] = rules[component.prop] || [];
                  component.patterns.forEach((pattern) => {
                    rules[component.prop].push({ pattern: eval(pattern.reg), message: pattern.msg, trigger: "blur" });
                  });
                }
              }
            }
          });
        });

      this.gridtables = gridtables;
      this.rules = rules;
      this.components = components;

      this.myFormInfo = formInfo;
      this.originalTabList = formInfo.tabList;
      this.formActiveName = "tab0";

      // 加载脚本
      await this.beforeFormSetData();

      if (this.isUpdate) {
        this.oldFormData = this.$deepClone(this.formData);
      }

      this.$nextTick(() => {
        this.ready = true;
      });
    },
    resetFormData() {
      this.ready = false;
    },
    // 校验表单数据
    validateForm() {
      return new Promise((resolve) => {
        this.$refs.form.validate(async (valid) => {
          if (valid) {
            const gridtables = this.gridtables;
            let gridValid = true;
            try {
              gridtables.forEach((item) => {
                gridValid = this.$refs[item.prop][0].validate();
                if (!gridValid) {
                  throw new Error();
                }
              });
            } catch (error) {}

            if (gridValid) {
              gridValid = await this.validateEvent();
            }

            resolve(gridValid);
          } else {
            this.$message({
              type: "error",
              message: this.$t(`表单有未正确填写项,请检查!`),
            });
            resolve(false);
          }
        });
      });
    },
    getComponentMap() {
      const componentMap = {};
      const formInfo = this.$deepClone(this.formInfo);
      formInfo.tabList.forEach((tab) => {
        tab.components.forEach((component) => {
          componentMap[component.prop] = component;
        });
      });
      return componentMap;
    },
    getForm() {
      // 获取表单数据
      return this.$deepClone(this.formData);
    },
    async setForm(postData) {
      return this.init(postData);
    },

    // 比对数据修改
    getDiffFormData() {
      const diffFormData = [];
      if (this.oldFormData == null) {
        return diffFormData;
      }
      for (let key in this.oldFormData) {
        const componentM = this.components[key];
        const oldValue = this.oldFormData[key];
        const newValue = this.formData[key];
        if (
          componentM &&
          ![
            "gridtable",
            "divider",
            "upload",
            "uploadimg",
            "company",
            "department",
            "createuser",
            "modifyuser",
            "createtime",
            "modifytime",
            "viewtable",
            "card",
            "btn",
          ].includes(componentM.type) &&
          oldValue != newValue
        ) {
          const dataPoint = {
            // 数据变动
            table_Name: componentM.table,
            tableField: componentM.field,
            formColumn: componentM.label,
            oldVal: oldValue,
            newVal: newValue,
            oldShowVal: "",
            newShowVal: "",
            creator: this.loginInfo.f_RealName + "/" + this.loginInfo.f_Account,
          };
          dataPoint.oldShowVal = this.getLabel(key, this.oldFormData);
          dataPoint.newShowVal = this.getLabel(key, this.formData);

          diffFormData.push(dataPoint);
        }
      }
      return diffFormData;
    },
    findTreeItem(arr, res) {
      arr.forEach((t) => {
        res.push({ value: t.value, label: t.label });
        if (t.children) {
          this.findTreeItem(t.children, res);
        }
      });
    },

    // 表单调整显示组件
    toShowData(data) {
      // 转化成显示数据
      const tabList = this.$deepClone(data);
      const pMap = {};
      tabList.forEach((tab) => {
        const componentList = [];
        tab.components.forEach((component) => {
          if (["card"].includes(component.type)) {
            if (!pMap[component.prop]) {
              pMap[component.prop] = [];
            }
            component.children = pMap[component.prop];
          }
          if (component.ptype == "card") {
            if (!pMap[component.pid]) {
              pMap[component.pid] = [];
            }
            pMap[component.pid].push(component);

            delete component.pid;
            delete component.ptype;
          } else {
            componentList.push(component);
          }
        });
        tab.components = componentList;
      });
      this.toFilterCard(tabList);
      return tabList;
    },
    toFilterCard(tabList) {
      tabList.forEach((tab) => {
        const componentList = [];
        tab.components.forEach((component) => {
          if (["card"].includes(component.type)) {
            component.children = this.toFilterCardSub(component.children);
            if (component.children.length > 0) {
              componentList.push(component);
            }
          } else {
            componentList.push(component);
          }
        });
        tab.components = componentList;
      });
    },
    toFilterCardSub(cardList) {
      const list = [];
      cardList.forEach((cardComponent) => {
        if (cardComponent.type != "card") {
          list.push(cardComponent);
        } else {
          cardComponent.children = this.toFilterCardSub(cardComponent.children);
          if (cardComponent.children.length > 0) {
            list.push(cardComponent);
          }
        }
      });
      return list;
    },

    // 获取表单初始值的设置
    getFormDataValue(component, data, isUpdate) {
      const res = [];
      if (component.type == "gridtable") {
        const tableData = data[component.table] || [];
        for (let i = 0, len = tableData.length; i < len; i++) {
          const row = tableData[i];
          const rowTmp = {};
          for (let j = 0, jlen = component.children.length; j < jlen; j++) {
            const cell = component.children[j];
            let cellValue = row[cell.field.toLowerCase()];
            if (!this.$validatenull(cellValue)) {
              if (["slider", "rate"].includes(cell.type)) {
                cellValue = parseInt(cellValue);
                if (isNaN(cellValue)) {
                  cellValue = 0;
                }
              }

              rowTmp[cell.prop] = cellValue;
            }
          }
          res.push(rowTmp);
        }
        return res;
      } else {
        let resValue;

        if (data[component.table] && data[component.table][0]) {
          resValue = data[component.table][0][component.field.toLowerCase()];
        } else if (!isUpdate) {
          resValue = component.default;
          if (component.isLogin && this.loginInfo) {
            switch (component.type) {
              case "companySelect":
                resValue = this.loginInfo.f_CompanyId;
                break;
              case "departmentSelect":
                resValue = this.loginInfo.f_DepartmentId;
                break;
              case "userSelect":
                resValue = this.loginInfo.f_UserId;
                break;
            }
          }
        }

        if (["switch"].includes(component.type)) {
          resValue =
            this.toValueType(component.valueType, resValue) ||
            this.toValueType(component.valueType, component.inactiveValue);
        } else if (
          ["select", "radio", "checkbox", "treeselect", "layerselect"].includes(component.type) &&
          component.dataType == "2" &&
          !this.$validatenull(resValue)
        ) {
          resValue = resValue + "";
        } else if (["slider", "rate"].includes(component.type) && !this.$validatenull(resValue)) {
          resValue = parseInt(resValue);
          if (isNaN(resValue)) {
            resValue = 0;
          }
        }

        return resValue;
      }
    },
    toValueType(type, value) {
      if (!this.$validatenull(value) && !this.$validatenull(type)) {
        switch (type) {
          case "boolean":
            return value == "true";
          case "string":
            return value;
          case "number":
            return Number(value);
        }
      }
    },

    // 编辑表格操作方法
    getTableColumns(children) {
      const columns = [];
      children.forEach((col) => {
        columns.push({
          id: col.prop,
          isHidden: !col.display,
          prop: col.prop,
          label: col.label,
          width: col.labelWidth,
          required: col.required,
          patterns: col.patterns,
        });
      });
      return columns;
    },
    handleAddRow(myTable) {
      let point = {};
      myTable.children.forEach((col) => {
        if (
          !["guid", "createtime", "modifytime", "company", "department", "createuser", "modifyuser"].includes(col.type)
        ) {
          point[col.prop] = col.default || undefined;
        } else {
          point[col.prop] = "";
        }

        if (!col.display) {
          switch (col.type) {
            case "guid":
              point[col.prop] = this.$uuid();
              break;
            case "company":
              if (this.loginInfo) {
                point[col.prop] = this.loginInfo.f_CompanyId;
              }
              break;
            case "department":
              if (this.loginInfo) {
                point[col.prop] = this.loginInfo.f_DepartmentId;
              }
              break;
            case "createuser":
              if (this.loginInfo) {
                point[col.prop] = this.loginInfo.f_UserId;
              }
              break;
            case "modifyuser":
              if (this.loginInfo) {
                point[col.prop] = this.loginInfo.f_UserId;
              }
              break;
            case "createtime":
              point[col.prop] = this.$getDayTime();
              break;
            case "modifytime":
              point[col.prop] = this.$getDayTime();
              break;
          }
        }
      });
      this.formData[myTable.prop].push(point);
    },
    handleDeleteRow(event, myTable) {
      this.formData[myTable.prop].splice(event.index, 1);
    },
    filterTableDeleteBtn(row) {
      if (row.hasNoDeleteBtn) {
        return false;
      } else {
        return true;
      }
    },

    // 表单脚本处理方法
    getEventParams({ prop, data, tableProp, tableIndex, tableRow, callback }) {
      // 获取脚本参数
      const loginUser = this.loginInfo;
      const params = {
        prop: prop,
        data: data,
        tableProp: tableProp,
        tableIndex: tableIndex,
        isUpdate: this.isUpdate,
        get: this.getValue,
        set: this.setValue,
        getLabel: this.getLabel,
        setRequired: this.setRequired,
        setDisabled: this.setDisabled,
        setHide: this.setHide,
        loading: this.showLoading,
        hideLoading: this.hideLoading,
        message: this.showMessage,
        httpGet: this.httpGet,
        httpPost: this.httpPost,
        httpDelete: this.httpDelete,
        httpPut: this.httpPut,
        loginUser: loginUser,
        callback: callback,
      };
      if (tableProp) {
        params.getLabel = (id) => {
          return this.getLabel(id, tableRow);
        };
      }

      return params;
    },
    getEvent(strEvent) {
      // 获取事件方法
      if (!this.$validatenull(strEvent)) {
        if (strEvent.indexOf("=>") != -1) {
          // 表示是老版本，提示其修改为新的版本
          console.warn("当前脚本不支持ES6语法，只支持ES5语法");
          return { res: false, msg: "脚本没有更新为最新的版本！" };
        } else {
          strEvent = `(function(){function fn(learun) {${strEvent}} return fn})()`;
          return this.$getFunction(strEvent);
        }
      } else {
        return { res: false, msg: "没设置脚本函数！" };
      }
    },

    beforeFormSetData() {
      // 表单初始化，新增和编辑都是执行的
      return new Promise((resolve) => {
        const myEvent = this.getEvent(this.myFormInfo.beforeSetData);
        if (myEvent.res) {
          const res = myEvent.fn(
            this.getEventParams({
              callback: (res) => {
                // 兼容异步回调方法
                resolve(res);
              },
            })
          );
          if (res != "callback") {
            resolve(res);
          }
        } else {
          resolve(true);
        }
      });
    },

    afterSaveEvent(formData) {
      // 表单初始化，新增和编辑都是执行的
      return new Promise((resolve) => {
        const myEvent = this.getEvent(this.myFormInfo.afterSaveEvent);
        if (myEvent.res) {
          this.formData = this.COPY(formData);
          const res = myEvent.fn(
            this.getEventParams({
              callback: (res) => {
                // 兼容异步回调方法
                resolve(res);
              },
            })
          );
          if (res != "callback") {
            resolve(res);
          }
        } else {
          resolve(true);
        }
      });
    },

    validateEvent() {
      // 表单初始化，新增和编辑都是执行的
      return new Promise((resolve) => {
        const myEvent = this.getEvent(this.myFormInfo.afterValidateForm);
        if (myEvent.res) {
          const res = myEvent.fn(
            this.getEventParams({
              callback: (res) => {
                // 兼容异步回调方法
                resolve(res);
              },
            })
          );
          if (res != "callback") {
            resolve(res);
          }
        } else {
          resolve(true);
        }
      });
    },

    formDataChangeEvent(prop, data) {
      // 表单数据改变执行脚本
      const myEvent = this.getEvent(this.myFormInfo.changeDataEvent);
      if (myEvent.res) {
        myEvent.fn(this.getEventParams({ prop, data }));
      }
    },

    tableDataChangeEvent(prop, data, tableComponent, tableIndex, tableRow) {
      if (tableComponent) {
        const myEvent = this.getEvent(tableComponent.changeDataEvent);
        if (myEvent.res) {
          myEvent.fn(this.getEventParams({ prop, data, tableProp: tableComponent.prop, tableIndex, tableRow }));
        }
      }
    },

    componentDataChangeEvent(prop, data) {
      // 组件数据改变执行脚本
      const component = this.components[prop];
      if (component) {
        const myEvent = this.getEvent(component.changeCode);
        if (myEvent.res) {
          myEvent.fn(this.getEventParams({ prop, data }));
        }
      }
    },

    componentBtnClick(component) {
      const myEvent = this.getEvent(component.clickCode);
      if (myEvent.res) {
        myEvent.fn(this.getEventParams({}));
      }
    },

    // 表单提供给脚本的方法
    getValue(path) {
      const paths = path.split(".");
      let data = this.formData;
      for (let i = 0, len = paths.length; i < len; i++) {
        data = data[paths[i]];
      }
      return data;
    },
    setValue({ path, value, type }) {
      if (type == "addTable") {
        this.formData[path].push(value);
      } else if (type == "deleteTable") {
        const paths = path.split(".");
        this.formData[paths[0]].splice(paths[1], 1);
      } else {
        const paths = path.split(".");
        if (paths.length == 2) {
          this.$set(this.formData[paths[0]], paths[1], value);
        } else if (paths.length == 3 && this.formData[paths[0]]) {
          this.$set(this.formData[paths[0]][paths[1]], paths[2], value);
        } else {
          this.$set(this.formData, path, value);
        }
      }
    },
    getLabel(id, formData) {
      if (formData == null) {
        formData = this.formData;
      }
      const v = formData[id];

      const componentM = this.components[id];
      switch (componentM.type) {
        case "radio":
        case "select":
        case "treeselect":
        case "layerselect":
        case "checkbox":
        case "selectMultiple":
          if (componentM.dataType == "3") {
            if (componentM.upCtrl) {
              if (formData && formData[componentM.upCtrl]) {
                const upCtrlVal = formData[componentM.upCtrl];
                return this.lr_dataSourceName(
                  this.lr_dataSourceDataByParamter[`${componentM.dataCode}_${upCtrlVal}`],
                  v,
                  componentM.dataValueKey,
                  componentM.dataLabelKey
                );
              }
            } else {
              return this.lr_dataSourceName(
                this.lr_dataSourceData[componentM.dataCode],
                v,
                componentM.dataValueKey,
                componentM.dataLabelKey
              );
            }
          } else if (componentM.dataType == "2") {
            return this.lr_dataItemName(this.lr_dataItem[componentM.dataCode], v);
          } else {
            const dataSource = [];
            this.findTreeItem(componentM.options, dataSource); //静态数据
            return this.lr_dataSourceName(dataSource, v, "value", "label");
          }
          break;
        case "companySelect":
          return this.lr_loadCompanyName(v);
        case "departmentSelect":
          return this.lr_departmentNameByOne(v);
        case "userSelect":
          return this.lr_userName(v);
        case "areaselect":
          return this.lr_areasName(v);
      }
      return v;
    },
    setRequired(prop, isRequired = true) {
      const component = this.components[prop];
      if (component) {
        this.$set(component, "required", isRequired);
        if (!component.subfield) {
          const rules = (this.rules[prop] || []).filter((t) => !t.required);
          if (isRequired) {
            rules.push({ required: true, message: `请输入${component.label}`, trigger: "blur" });
          }
          this.$set(this.rules, component.prop, rules);
        }
      }
    },
    setDisabled(prop, isDisabled = true) {
      const component = this.components[prop];
      if (component) {
        this.$set(component, "disabled", isDisabled);
      }
    },
    setHide(prop, isHide = true) {
      const component = this.components[prop];
      if (component) {
        this.$set(component, "display", !isHide);
      }
    },
    showLoading(text) {
      this.loadingObj = this.$loading({
        lock: true,
        text: text || "加载中",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.4)",
      });
    },
    hideLoading() {
      this.loadingObj && this.loadingObj.close();
    },
    showMessage(text, type = "warning") {
      this.$message({
        type: type,
        message: text,
      });
    },
    async httpGet({ url, params, callback }) {
      const res = await this.$awaitWraper(
        window.$axios({
          url: `${url}`,
          method: "get",
          params,
        })
      );
      callback && callback(res);
    },
    async httpPost({ url, params, data, callback }) {
      const res = await this.$awaitWraper(
        window.$axios({
          url: `${url}`,
          method: "post",
          params,
          data,
        })
      );
      callback && callback(res);
    },
    async httpPut({ url, params, data, callback }) {
      const res = await this.$awaitWraper(
        window.$axios({
          url: `${url}`,
          method: "put",
          params,
          data,
        })
      );
      callback && callback(res);
    },
    async httpDelete({ url, params, data, callback }) {
      const res = await this.$awaitWraper(
        window.$axios({
          url: `${url}`,
          method: "delete",
          params,
          data,
        })
      );
      callback && callback(res);
    },

    handleItemChange({ prop, obj }, tableComponent, tableIndex, tableRow) {
      // 子表改变事件
      if (tableComponent) {
        this.tableDataChangeEvent(prop, obj, tableComponent, tableIndex, tableRow);
      } else {
        this.componentDataChangeEvent(prop, obj);
        this.formDataChangeEvent(prop, obj);
      }
    },
  },
};
</script>

<style lang="less">
@import "./index.less";
</style>
